# -*- coding: utf-8 -*-
from django.conf import settings
from qcloud_cos import CosConfig, CosServiceError
from qcloud_cos import CosS3Client


def create_bucket(bucket, region='ap-nanjing'):
    """创建桶"""
    
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    client = CosS3Client(config)
    
    # private/public-read/public-read-write
    client.create_bucket(Bucket=bucket, ACL='public-read')
    
    # cos解决跨域
    cors_config = {
        'CORSRule': [
            {
                'AllowedOrigin': '*',
                'AllowedMethod': ['GET', 'PUT', 'HEAD', 'POST', 'DELETE'],
                'AllowedHeader': '*',
                'ExposeHeader': '*',
                'MaxAgeSeconds': 500
            }
        ]
    }
    client.put_bucket_cors(Bucket=bucket, CORSConfiguration=cors_config)


def upload_file(bucket, region, file_obj, key):
    """上传文件"""
    
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    client = CosS3Client(config)
    
    # 上传图片对象
    response = client.upload_file_from_buffer(
        Bucket=bucket,
        Body=file_obj,
        Key=key,
    )
    
    # 返回图地址
    return 'https://{}.cos.{}.myqcloud.com/{}'.format(bucket, region, key)


def delete_file(bucket, region, key):
    """删除文件"""
    
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    client = CosS3Client(config)
    
    client.delete_object(
        Bucket=bucket,
        Key=key,
    )


def delete_file_list(bucket, region, key_list):
    """批量删除文件"""
    
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    client = CosS3Client(config)
    
    objects = {
        "Quiet": "true",
        "Object": key_list
    }
    
    client.delete_objects(
        Bucket=bucket,
        Delete=objects,
    )


def credential(bucket, region):
    """获取临时凭证"""
    
    from sts.sts import Sts
    
    config = {
        # 临时秘钥有效时长，秒
        'duration_seconds': 1800,
        # 固定秘钥 id
        'secret_id': settings.TENCENT_COS_ID,
        # 固定秘钥 key
        'secret_key': settings.TENCENT_COS_KEY,
        # 桶
        'bucket': bucket,
        # 区域
        'region': region,
        #
        'allow_prefix': '*',
        # 操作权限 https://cloud.tencent.com/document/product/436/31923
        'allow_actions': [
            # 'name/cos:PutObject',
            # 'name/cos:PostObject',
            # 'name/cos:DeleteObject',
            # 'name/cos:UploadPart',
            # 'name/cos:UploadPartCopy',
            # 'name/cos:CompleteMultipartUpload',
            # 'name/cos:AbortMultipartUpload',
            '*'
        ],
    }
    sts = Sts(config)
    result_dict = sts.get_credential()
    
    return result_dict


def check_file(bucket, region, key):
    """验证文件"""
    
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    client = CosS3Client(config)
    
    data = client.head_object(
        Bucket=bucket,
        Key=key,
    )
    
    return data


def delete_bucket(bucket, region):
    """删除cos桶"""
    
    config = CosConfig(Region=region, SecretId=settings.TENCENT_COS_ID, SecretKey=settings.TENCENT_COS_KEY)
    client = CosS3Client(config)
    
    try:
        # 删除文件
        while 1:
            part_objects = client.list_objects(bucket)
            contents = part_objects.get('Contents')
            if not contents:
                break
            
            objects = {
                "Quiet": "true",
                "Object": [{'Key': item['Key']} for item in contents]
            }
            
            client.delete_objects(Bucket=bucket, Delete=objects)
            
            if not part_objects['IsTruncated'] == "false":
                break
        
        # 删除碎片
        while 1:
            part_uploads = client.list_multipart_uploads(bucket)
            uploads = part_uploads.get('Upload')
            if not uploads:
                break
            
            for item in uploads:
                client.abort_multipart_upload(bucket, item['Key'], item['UploadId'])
            
            if not part_uploads['IsTruncated'] == "false":
                break
        
        # 删除桶
        client.delete_bucket(bucket)
    except CosServiceError:
        pass
